package com.android.waterdetection;

import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.waterdetection.adapter.UserManagerAdapter;
import com.android.waterdetection.bean.UserBean;
import com.android.waterdetection.dao.DBService;
import com.android.waterdetection.event.AdminAddData;
import com.android.waterdetection.event.AdminDeleteData;
import com.android.waterdetection.event.AdminQuestData;
import com.android.waterdetection.utils.ToastUtil;
import com.yanzhenjie.recyclerview.OnItemMenuClickListener;
import com.yanzhenjie.recyclerview.SwipeMenuCreator;
import com.yanzhenjie.recyclerview.SwipeMenuItem;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;
import com.yanzhenjie.recyclerview.widget.DefaultItemDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

public class AdminActivity extends AppCompatActivity {

    private static final String TAG = "AdminActivity";

    private SwipeRecyclerView mRvUser;
    private UserManagerAdapter mUserManagerAdapter;

    protected RecyclerView.ItemDecoration mItemDecoration;

    private List<UserBean> mUserBeans;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin);
        EventBus.getDefault().register(this);
        this.getSupportActionBar().hide();

        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    private void initData() {

        new Thread(() -> {
            mUserBeans = DBService.queryUser();

            Log.d(TAG, "initData-mUserBeans->" + mUserBeans);
            if (mUserBeans != null) {
                EventBus.getDefault().post(new AdminQuestData(true));
            } else {
                EventBus.getDefault().post(new AdminQuestData(false));
            }
        }).start();
    }

    private void initView() {
        mRvUser = findViewById(R.id.recycler_view);

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getQuestDataStatus(AdminQuestData event) {
        Log.d(TAG, "event.isQuestDataSuccess()-->" + event.isQuestDataSuccess());

        if (event.isQuestDataSuccess()) {
            mRvUser.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
            mUserManagerAdapter = new UserManagerAdapter(this, mUserBeans);
            mRvUser.setSwipeMenuCreator(swipeMenuCreator);
            mRvUser.setOnItemMenuClickListener(mMenuItemClickListener);
            mItemDecoration = new DefaultItemDecoration(ContextCompat.getColor(this, R.color.yellow));
            mRvUser.addItemDecoration(mItemDecoration);
            mRvUser.setAdapter(mUserManagerAdapter);
        } else {
            ToastUtil.showToast(this, "查询用户为空");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getDeleteDataStatus(AdminDeleteData event) {
        Log.d(TAG, "event.isDeleteDataSuccess()-->" + event.isDeleteDataSuccess());
        Log.d(TAG, "event.getDeleteDataPosition()-->" + event.getDeleteDataPosition());

        if (event.isDeleteDataSuccess()) {
            mUserBeans.remove(event.getDeleteDataPosition());
            mUserManagerAdapter.notifyDataSetChanged();
            ToastUtil.showToast(this, "删除第" + event.getDeleteDataPosition() + 1 + "个数据成功");
        } else {
            ToastUtil.showToast(this, "删除第" + event.getDeleteDataPosition() + 1 + "个数据失败");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getAddDataStatus(AdminAddData event) {
        Log.d(TAG, "event.isAddDataSuccess()-->" + event.isAddDataSuccess());
        Log.d(TAG, "event.getAddDataUser()-->" + event.getAddDataUser());
        Log.d(TAG, "event.getAddDataPass()-->" + event.getAddDataPass());

        if (event.isAddDataSuccess()) {
            UserBean userBean = new UserBean();
            userBean.setUsername(event.getAddDataUser());
            userBean.setPassword(event.getAddDataPass());
            mUserBeans.add(userBean);
            mUserManagerAdapter.notifyDataSetChanged();
            ToastUtil.showToast(this, "添加用户信息成功");
        } else {
            ToastUtil.showToast(this, "添加用户信息失败，用户已存在");
        }
    }

    /**
     * 菜单创建器，在Item要创建菜单的时候调用。
     */
    private SwipeMenuCreator swipeMenuCreator = (swipeLeftMenu, swipeRightMenu, position) -> {
        int width = getResources().getDimensionPixelSize(R.dimen.dp_90);

        // 1. MATCH_PARENT 自适应高度，保持和Item一样高;
        // 2. 指定具体的高，比如80;
        // 3. WRAP_CONTENT，自身高度，不推荐;
        int height = ViewGroup.LayoutParams.MATCH_PARENT;

        {
            SwipeMenuItem deleteItem = new SwipeMenuItem(AdminActivity.this).setBackground(R.drawable.selector_red)
                    .setImage(R.drawable.ic_action_delete)
                    .setText("删除")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(deleteItem);// 添加菜单到右侧。


            SwipeMenuItem addItem = new SwipeMenuItem(AdminActivity.this).setBackground(R.drawable.selector_green)
                    .setImage(R.drawable.ic_action_add)
                    .setText("添加")
                    .setTextColor(Color.WHITE)
                    .setWidth(width)
                    .setHeight(height);
            swipeRightMenu.addMenuItem(addItem); // 添加菜单到右侧。

        }
    };

    /**
     * RecyclerView的Item的Menu点击监听。
     */
    private OnItemMenuClickListener mMenuItemClickListener = (menuBridge, position) -> {
        menuBridge.closeMenu();

        int direction = menuBridge.getDirection(); // 左侧还是右侧菜单。
        int menuPosition = menuBridge.getPosition(); // 菜单在RecyclerView的Item中的Position。

        Log.d(TAG,"menuPosition--->" + menuPosition);
        if (direction == SwipeRecyclerView.RIGHT_DIRECTION) {
            if (menuPosition == 0) {
                //删除
                UserBean userBean = mUserBeans.get(position);
                new Thread(() -> {
                    boolean deleteUser = DBService.deleteUser(userBean.getUsername());
                    EventBus.getDefault().post(new AdminDeleteData(deleteUser, position));
                }).start();
            } else {
                //添加
                View dialogView = LayoutInflater.from(this).inflate(R.layout.item_dialog_admin_add_user, null, false);
                EditText edtUser = dialogView.findViewById(R.id.edt_user);
                EditText edtPass = dialogView.findViewById(R.id.edt_pass);
                AlertDialog.Builder dialog = new AlertDialog.Builder(this);
                dialog.setTitle(this.getString(R.string.hint));
                dialog.setMessage("请输入添加的账号密码");
                dialog.setView(dialogView);
                dialog.setPositiveButton(this.getString(R.string.sure), (dialog1, which) -> {
                    String user = edtUser.getText().toString().trim();
                    String pass = edtPass.getText().toString().trim();
                    new Thread(() -> {
                        boolean isCz = DBService.queryUserIsCz(user);
                        if (isCz) {
                            boolean addUser = DBService.insertUser(user,pass);
                            EventBus.getDefault().post(new AdminAddData(addUser,user,pass));
                        } else {
                            EventBus.getDefault().post(new AdminAddData(false,null,null));
                        }

                    }).start();
                    dialog1.dismiss();
                });
                dialog.setNegativeButton(this.getString(R.string.cancel), null);
                dialog.create().show();
            }

        }
    };
}